<?php
/**
 * This file is part of webman.
 *
 * Licensed under The MIT License
 * For full copyright and license information, please see the MIT-LICENSE.txt
 * Redistributions of files must retain the above copyright notice.
 *
 * @author    walkor<walkor@workerman.net>
 * @copyright walkor<walkor@workerman.net>
 * @link      http://www.workerman.net/
 * @license   http://www.opensource.org/licenses/mit-license.php MIT License
 */
namespace support\exception;

use Webman\Http\Request;
use Webman\Http\Response;
use Throwable;
use Webman\Exception\ExceptionHandler;
use Webman\Exception\FileException;
use Webman\Exception\NotFoundException;
use support\exception\ValidateException;
use support\exception\HttpException;
use think\db\exception\PDOException;
use Webman\Event\Event;




/**
 * Class Handler
 * @package support\exception
 */
class Handle extends ExceptionHandler
{
	
	
	private $error_log_db = true;	//异常日志是否写入数据库
	
	
	public $dontReport = [
		HttpException::class,
		ValidateException::class,
		PDOException::class,
    ];
	
    public function report(Throwable $exception)
    {
        parent::report($exception);
    }

    public function render(Request $request, Throwable $exception) : Response
    {
		$status = $exception->getCode();
		
		if($exception instanceof NotFoundException) {
            return json(['msg'=>$exception->getMessage(),'status'=>411]);
        }
		
		if($exception instanceof FileException) {
            return json(['msg'=>$exception->getMessage(),'status'=>411]);
        }
		
		if($exception instanceof ValidateException) {
            return json(['msg'=>$exception->getMessage(),'status'=>$status ? $status : 411]);
        }
		
		$event['username'] = session('admin.username');
		
		
		
        if($exception instanceof PDOException) {
			if($this->error_log_db){
				$event['msg'] = $exception->getMessage();
				Event::emit('exceptionLog', $event);
			}
			return json(['msg'=>config('app.debug') ? $exception->getMessage() : '系统错误','status'=>500]);
        }
		
		
        return parent::render($request, $exception);
    }

}